package dao.impl;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Repository;

import pojo.Customer;
import dao.CustomerDao;

@Repository(value="customerDao")
public class CustomerDaoImpl implements CustomerDao {
	@Resource(name="sss")
	private EntityManagerFactory factory;
	private ApplicationContext context;
	private EntityManager manager;

	public CustomerDaoImpl() {

	}

	@Override
	public Customer addCustomer(Customer c) {
		 manager = factory.createEntityManager();
		EntityTransaction tx = manager.getTransaction();
		
		Query query = manager.createQuery("from Customer where cname='" + c.getCname() + "'");
		if(query.getResultList().size() == 0){//重复不插入
			tx.begin();
			manager.persist(c);
			tx.commit();
			return c;
		}
		else{
			return null;
		}
	}

	@Override
	public Customer findCustomer(String cname, String psd) {
		Query query = manager.createQuery("from Customer where cname='" + cname + "' and password='" + psd + "'");
		if(query.getResultList().size() == 0){
			return null;
		}
		else{
			Customer c1 = (Customer)query.getSingleResult();
			return c1;
		}
	}

}